package com.bosssoft.hr.javase;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.UUID;

public class HttpFileDownloader {

    public boolean download(String url) {
        try {
            this.downloadByUrl(url);
            return true;
        } catch (IOException e) {
            System.err.println("文件下载出错，请重新尝试");
            return false;
        }
    }

    public String downloadByUrl(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);

        //文件保存位置
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        File file = new File(FileConf.filepath + uuid + ".xml");

        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if (fos != null) {
            fos.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
        System.out.println("download xml file: " + url + " success and saved local " + uuid + ".xml");
        return uuid;
    }

    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[2 * 1024]; // 1kb
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
           // System.out.println(Arrays.toString(buffer).toString());
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    public static void main(String[] args) throws IOException {
        boolean download = new HttpFileDownloader().download("http://58.22.61.222:57903/javasexml/user.xml");

        System.out.println(download);
    }
}
